﻿using AutoMapper;
using Common.Domain;
using Common.Infrastructure.Repository;
using Common.Services;
using MediatR;
using System.Security.Cryptography;
using System.Text;

namespace Business.ReadAPI.Application.Accounts
{
    /// <summary>
    /// 
    /// </summary>
    public class LoginRequestHandler : IRequestHandler<LoginRequestModel, APIResult>
    {
        /// <summary>
        /// 注入仓储
        /// </summary>
        private IBaseRepository<Account> accountRepository;
        /// <summary>
        /// 注入自动映射
        /// </summary>
        private readonly IMapper mapper;
        public LoginRequestHandler(IBaseRepository<Account> accountRepository, IMapper mapper)
        {
            this.accountRepository = accountRepository;
            this.mapper = mapper;
        }
        public Task<APIResult> Handle(LoginRequestModel request, CancellationToken cancellationToken)
        {
            APIResult result = new APIResult();
            result.Code = EnumCode.LoginSuccess;
            result.Msg = "登录成功";

           
            var entity = accountRepository.GetAll().FirstOrDefault(x => x.AccountName == request.AccountName && x.AccountPwd == request.AccountPwd);
            if (entity == null)
            {
                result.Code = EnumCode.LoginFailure;
                result.Msg = "账号或密码错误";
                return Task.FromResult(result);
            }
            //自动映射
            LoginResponseModel responseModel = mapper.Map<LoginResponseModel>(entity);
            responseModel.RoleName = ((SystemRole)responseModel.RoleId).ToString();
            result.Data = responseModel;


            return Task.FromResult(result);
        }
    }
    /// <summary>
    /// 
    /// </summary>
    public class LoginRequestModel:IRequest<APIResult>
    {
        public string AccountName { get; set; }
        public string AccountPwd { get; set; }
    }
    /// <summary>
    /// 
    /// </summary>
    public class LoginResponseModel
    {
        public int AccountId { get; set; }
        public string AccountName { get; set; }
        public string AccountPwd { get; set; }
        public string AccountNicName { get; set; }
        public string AccountPhone { get; set; }
        public bool IsDisable { get; set; }
        public int RoleId { get; set; }
        public string RoleName { get; set; }
    }

}
